﻿using Core.SimpleTemp.Common;
using Core.Toolkit.Common;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Core.Toolkit.AutoMapperExtend.DataDictionary
{

    public class DataDicPool : IDataDicPool
    {

        IServiceProvider _serviceProvider;
        Dictionary<string, string> _dataDic = new Dictionary<string, string>();
        /// <summary>
        /// 以Category分组
        /// </summary>
        Dictionary<string, List<DataDicModel>> _dataDicListByCategory = new Dictionary<string, List<DataDicModel>>();


        public DataDicPool(IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider;
            Initialization();
        }
        private void Initialization()
        {
            using (var scope = _serviceProvider.CreateScope())
            {
                var services = scope.ServiceProvider;
                var dataDicProviders = services.GetRequiredService<IEnumerable<IDataDicProvider>>();
                foreach (IDataDicProvider provider in dataDicProviders)
                {
                    provider.LoadData(_dataDic, _dataDicListByCategory);
                }
            }
        }

        public string GetDicValue(string category, string key)
        {
            string value;
            if (_dataDic.TryGetValue($"{category}_{key}", out value))
                return value;
            else
                return null;
        }

        private List<DataDicModel> GetDicObjListByCategory(string category)
        {
            _dataDicListByCategory.TryGetValue(category, out List<DataDicModel> value);
            return value;
        }

        public List<KeyValue<string, string>> GeDataDicValueByCategory(string category)
        {
            var list = this.GetDicObjListByCategory(category);
            return list?.Select(obj => new KeyValue<string, string> { Key = obj.Key, Value = obj.Value })?.ToList();
        }

        public List<KeyValue<string, List<KeyValue<string, string>>>> GeDataDicValueByCategory(params string[] categorys)
        {
            List<KeyValue<string, List<KeyValue<string, string>>>> ret = new List<KeyValue<string, List<KeyValue<string, string>>>>();
            foreach (var item in categorys)
            {
                var list = this.GeDataDicValueByCategory(item);
                ret.Add(new KeyValue<string, List<KeyValue<string, string>>>() { Key = item, Value = list });
            }
            return ret;
        }
    }


    [AutoDi(typeof(DataDicPool), AutoDiAttribute.Singleton)]
    public interface IDataDicPool
    {
        string GetDicValue(string category, string key);
        List<KeyValue<string, List<KeyValue<string, string>>>> GeDataDicValueByCategory(params string[] categorys);
        List<KeyValue<string, string>> GeDataDicValueByCategory(string category);
    }
}

